<style>
    #container {
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        padding: 0;
        box-sizing: border-box;
        overflow: hidden;
        background: white;
    }

    .menu {
        width: 100px;
        font-size: 14px;
        border: 1px solid #ccc;
        z-index: 1000;
        position: absolute;
        display: none;
        background: #fff;
    }

    .menu ul {
        margin: 0px;
        padding: 0px;
        text-align: center;
        list-style-type: none;
    }

    .menu ul li {
        padding: 5px 0px;
        font-size: 12px;
    }

    .menu ul li:hover {
        background: #e3e3e3;
    }

    .menu ul li a:link {
        color: #000;
        text-decoration: none;
    }

    /*  ::-webkit-scrollbar { !*滚动条整体样式*!
          width: 5px; !*高宽分别对应横竖滚动条的尺寸*!
          height: 1px;
      }

      ::-webkit-scrollbar-thumb { !*滚动条里面小方块*!
          border-radius: 10px;
          -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
          background: #535353;
      }

      ::-webkit-scrollbar-track { !*滚动条里面轨道*!
          -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
          border-radius: 10px;
          background: #EDEDED;
      }*/

    .edit {
        position: absolute;
        top: 100px;
        left: 0;
        right: 0;
        bottom: 20px;
        box-sizing: border-box;
    }

    #jsmind_container {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
</style>
<div id="container" class="fsh-rightPanel">
    <!--    <button class="layui-btn layui-btn-normal" id="btn-save">保存</button>
        <button class="layui-btn layui-btn-warm layui-btn-sm" id="btn-add">+新建目录</button>-->
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
        <legend>课程设计</legend>
    </fieldset>
    <div class="edit">
        <div id="jsmind_container"></div>

    </div>
</div>

<!--右侧菜单-->
<div id="divmenu" class="menu">
    <ul>
        <li onclick="expand_all()" class="pub">展开所有</li>
        <li onclick="collapse_all()" class="pub">合并所有</li>
        <li onclick="zoomIn()" class="pub">画布放大</li>
        <li onclick="zoomOut()" class="pub">画布缩小</li>
        <li onclick="add_node();" class="add">新增节点</li>
        <!--        <li onclick="add_upfile();" class="upload">上传文件</li>-->
<!--        <li onclick="show_selected();" class="sel">课程选择</li>-->
        <li onclick="remove_node()" class="delete">删除</li>
        <!--        <li onclick="move_node('up')" class="move">上移</li>-->
        <!--        <li onclick="move_node('down')" class="move">下移</li>-->
    </ul>
</div>

<script>
    var _jm;
    var diagram;
    var title = $("#title");
    var table;
    layui.use(['layer', 'table'], function () {
        var layer = layui.layer;
        table = layui.table;

        //  新增节点
        $('#btn-add').click(function () {
            addNewNode();
        });
        // 保存
        $('#btn-save').click(function () {
            save();
        });
        //选择老师
        $('#teacherName').click(function () {

        });
    });


    function load_jsmind() {
        var mind = {
            "meta": {
                "name": "demo",
                "author": "hizzgdev@163.com",
                "version": "0.2",
            },
            "format": "node_array",
            "data": [
                {"id": "root", "isroot": true, "topic": "杭州CG培养计划"},

                {"id": "sub1", "parentid": "root", "topic": "第一年"},
                {"id": "sub11", "parentid": "sub1", "topic": "CG基础"},
                {"id": "sub12", "parentid": "sub11", "topic": "教程1"},
                {"id": "sub13", "parentid": "sub11", "topic": "教程2"},

                {"id": "sub2", "parentid": "root", "topic": "第二年"},
                {"id": "sub14", "parentid": "sub1", "topic": "动画基础"},
                {"id": "sub15", "parentid": "sub14", "topic": "教程1"},
                {"id": "sub16", "parentid": "sub14", "topic": "教程2"},

                {"id": "sub3", "parentid": "root", "topic": "第三年"},
                {"id": "sub25", "parentid": "sub1", "topic": "引擎基础"},
                {"id": "sub26", "parentid": "sub25", "topic": "教程2",},
                {"id": "sub27", "parentid": "sub25", "topic": "教程4"},
            ]
        };
        var options = {
            container: 'jsmind_container',
            editable: true,
            theme: 'greensea'
        };
        _jm = jsMind.show(options, mind);

        $('#jsmind_container').mousedown(function (e) {
            if (e.which == 1) {  // 1 = 鼠标左键 left; 2 = 鼠标中键; 3 = 鼠标右键
                $("#divmenu").hide();
                $('#dialog-search-result').hide();
            }
        });

        $("#container").bind("contextmenu", function () {
            var div = $("#divmenu");
            if (showmenu()) div.css({
                "left": document.body.scrollLeft + event.clientX - 180,
                "top": document.body.scrollTop + event.clientY - 80
            }).show();

            return false;
        });
        //监听右侧菜单点击事件，发生点击则隐藏菜单层
        $("#divmenu").click(function (event) {
            var $this = $(event.target);
            $("#divmenu").hide();
        });
    }

    load_jsmind();

    function save() {
        console.log(diagram.model.toJson());
    }

    function load() {
        diagram.model = go.Model.fromJson(document.getElementById("data").value);
    }

    function addNewNode() {
        diagram.model.addNodeData({"key": "新增节点"});
    }

    //新增节点
    function add_node() {
        var selected_node = _jm.get_selected_node(); // as parent of new node
        if (!selected_node) {
            layer.msg('请选择一个节点！');
            return;
        }
        var nodeid = jsMind.util.uuid.newid();
        var topic = '未命名';
        var node = _jm.add_node(selected_node, nodeid, topic);

    }

    function appendHtml(name, users) {
        return "<div class='name' onclick='test()'>" + name + "</div><div class='user'><i class='dot-green'></i>" + users + "</div>";
    }

    function test() {
        console.log('aaaaaaaaaaaaa')
    }

    //上移、下移节点，direction(top,bottom)
    function move_node(direction) {
        var selected_node = _jm.get_selected_node();
        _jm.move_node(selected_node.id, "_first_");
    }

    //删除节点
    function remove_node() {
        var selected_node = _jm.get_selected_node(); // as parent of new node
        if (!selected_node) {
            layer.msg('请选择一个节点！');
            return;
        }
        console.log(selected_node)
        var isLastNode = selected_node.children.length;
        if (isLastNode > 0) {
            layer.msg('存在子集，不能删除！');
        } else {
            _jm.remove_node(selected_node.id);
        }
    }

    //关联人员
    function show_selected() {
        var selected_node = _jm.get_selected_node(); // as parent of new node
        if (!selected_node) {
            layer.msg('请选择一个节点！');
            return;
        }
        if (selected_node.id === 0) {
            layer.msg('根节点不支持查看！');
            return;
        }
        showDialog({
            title: '课程选择'
            , template: 'views/static/plan/template/check_video.html'
            , yes: function (index, layero) {
                layer.close(index);
            }
        })
        // showBigDialog({
        //     title: '选择老师'
        //     , template: 'views/static/courseware/template/teacher.html'
        //     , yes: function (index, layero) {
        //         var checkData = table.checkStatus('teacherTable').data;
        //         layer.close(index);
        //     }
        //
        // })
    }

    //展开选择的节点
    function expand() {
        var selected_id = get_selected_nodeid();
        if (!selected_id) {
            layer.msg('please select a node first.');
            return;
        }

        _jm.expand_node(selected_id);
    }

    //合并选择的节点
    function collapse() {
        var selected_id = get_selected_nodeid();
        if (!selected_id) {
            layer.msg('please select a node first.');
            return;
        }

        _jm.collapse_node(selected_id);
    }

    //展开所有节点
    function expand_all() {
        _jm.expand_all();
        $("#jsmind_container").offset({top: ((0 - _jm)), left: 100}); //将中心点调至屏幕中心
    }

    //合并所有节点
    function collapse_all() {
        _jm.collapse_all();
        $("#jsmind_container").offset({top: ((0 - _jm)), left: 100}); //将中心点调至屏幕中心
    }

    //画布缩小
    function zoomIn() {
        if (_jm.view.zoomIn()) {
            //zoomOutButton.disabled = false;
        } else {
            //zoomInButton.disabled = true;
        }
    }

    //画布放大
    function zoomOut() {
        if (_jm.view.zoomOut()) {
            //zoomInButton.disabled = false;
        } else {
            //  zoomOutButton.disabled = true;
        }
    }

    function dragFunc(id) {
        var Drag = document.getElementById(id);
        Drag.onmousedown = function (event) {
            var ev = event || window.event;
            event.stopPropagation();
            var disX = ev.clientX - Drag.offsetLeft;
            var disY = ev.clientY - Drag.offsetTop;
            document.onmousemove = function (event) {
                var ev = event || window.event;
                Drag.style.left = ev.clientX - disX + "px";
                Drag.style.top = ev.clientY - disY + "px";
                Drag.style.cursor = "move";
            };
        };
        Drag.onmouseup = function () {
            document.onmousemove = null;
            this.style.cursor = "default";
        };
    }


    //通过JS屏蔽自带右键菜单
    document.oncontextmenu = function (e) {
        return false;
    };

    //动态化展示右键菜单
    function showmenu() {
        var selected_node = _jm.get_selected_node(); // as parent of new node

        if (!selected_node) {
            $("#divmenu ul li:not(.pub)").hide();
            $("#divmenu ul li[class='pub']").show();
        } else {
            if ((selected_node.isroot || false)) {
                $("#divmenu ul li:not(.add)").hide();
                $("#divmenu ul li[class='add']").show();
            } else if (selected_node.data.leave == 1) {
                if (selected_node.children.length > 0) {
                    $(".pub,.update,.view,.history,.delete").hide();
                    $(".sel,.upload,.add,.move").show();
                } else {
                    $(".pub,.update,.view,.history").hide();
                    $(".sel,.upload,.add,.move,.delete").show();
                }
            } else {
                if (selected_node.children.length > 0) {
                    $(".pub,.view,.history,.update,.delete").hide();
                    $(".upload,.sel,.add,.move").show();
                } else {
                    if (selected_node.data.filepath == "null" || selected_node.data.filepath == undefined) {
                        $(".upload,.sel,.delete,.add,.move").show();
                        $(".pub,.view,.history,.update").hide();
                    } else {
                        $(".view,.delete,.update,.history,.move").show();
                        $(".pub,.sel,.upload,.add").hide();
                    }
                }
            }
        }
        return true;
    }


    //搜索
    function search() {
        var count = 0;
        if ($.trim($("#keywords").val()).length == 0) {
            InitJsMind();
        } else {
            //InitJsMind();
            $('jmnode').each(function (i, e) {
                var code = $(this).attr("code");
                if (code != undefined) {
                    code = $(this).attr("code").toLowerCase();
                    var filenode = "<span>" + $("#keywords").val().toLowerCase() + "</span>";
                    if ($(this).html().toLowerCase().indexOf($("#keywords").val().toLowerCase()) != -1 || $(this).html().toLowerCase().indexOf(filenode) != -1 || code.indexOf($("#keywords").val().toLowerCase()) != -1) {
                        $(this).addClass("root selected");
                        $(this).css("opacity", "0.9");
                        count = parseInt(count) + 1;
                        if (count == 1) {
                            auto_height();//恢复位置
                            console.log(code);
                            var jm2 = $(this).css("top").replace("px", ""); //获取当前点位置
                            $("#jsmind_container").offset({
                                top: ((0 - parseInt(jm2)) + ($("body").height() / 2)),
                                left: ($("body").width() / 10)
                            }); //将中心点调至屏幕中心
                        }
                    } else {
                        $(this).removeClass("root selected");
                        $(this).css("opacity", "0.1");  //没找到的元素透明的设高
                    }
                }
            });
            if (count == 0) {
                layer.msg('未检索到任何数据！');
            }
        }
    }

    //鼠标滚轮缩放
    // $('#jsmind_container').onmousewheel = document.onmousewheel = function (e) {
    //     e = e || window.event;
    //     if (e.wheelDelta) {  //判断浏览器IE，谷歌滑轮事件
    //         if (e.wheelDelta > 0) { //当滑轮向上滚动时
    //             _jm.view.zoomIn()
    //         }
    //         if (e.wheelDelta < 0) { //当滑轮向下滚动时
    //             _jm.view.zoomOut();
    //         }
    //     } else if (e.detail) {  //Firefox滑轮事件
    //         if (e.detail > 0) { //当滑轮向下滚动时
    //             _jm.view.zoomOut();
    //         }
    //         if (e.detail < 0) { //当滑轮向上滚动时
    //             _jm.view.zoomIn()
    //         }
    //     }
    // };

    //查询当前项目下的用户
    var projectUserData;
    var userList; //用户列表

    function loadProjectUserList() {
        get('/api/cgProjectUser?project_id=' + currentProjectId, null, function (result) {
            projectUserData = result.data;
            appendUserItem();
        });
    }

    function appendUserItem() {
        userList = $('#list-search-result');
        for (var i = 0; i < projectUserData.length; i++) {
            var html = ' <li > <div class="cb"><label style="width: 122px;"><input  type="checkbox" name="group" id="' + i + '"/>'
                + projectUserData[i].nickname + '</label><i class="dis_per"  onclick="dispatchPer(' + i + ')"></i></div></li>';
            userList.append(html);
        }

        userList.find("input").change(function () {
            var selected_node = _jm.get_selected_node();
            var oldIds = selected_node.data.user_ids;
            var inputs = userList.find("input:checked");
            var names = [];
            var ids = [];
            for (var i = 0; i < inputs.length; i++) {
                var index = $(inputs[i]).prop('id');
                var id = projectUserData[index].user_id;
                var name = projectUserData[index].nickname;
                ids[i] = id;
                names[i] = name;
            }
            var param = {
                duty_id: selected_node.data.duty_id,
                user_ids: ids.toString()
            };
            patch('/api/cgDuty/update', param, function (result) {
                selected_node.data.user_ids = ids.toString();
                _jm.update_node(selected_node.id, appendHtml(selected_node.data.duty_name, names.toString()))
            });

        });
        userList.click(function (e) {
            e.stopPropagation()
        });
    }

    //分配权限
    function dispatchPer(i) {
        var info = projectUserData[i];
        showDialog('../dialog/team_per_patch.html', ['450px', '280px'], function (layero, index) {
            var body = layer.getChildFrame('body', index);
            body.find('#name').val(info.nickname);
            body.find('#job').val(info.job);
            body.find('#phone').val(info.phone);

            body.find("#head_img").attr('src', info.photo);
            var inputs = body.find("#cb input");
            get("/api/cgDuty/getUserPer?project_id=" + currentProjectId + "&user_ids=" + info.user_id, null, function (result) {
                var pers = result.data.permission.split(',');
                for (var j = 0; j < inputs.length; j++) {
                    $(inputs[j]).prop('checked', pers[j + 1] == 1);
                }
            });
            var pers;
            body.find('#btn-save').click(function () {
                pers = [];
                for (var j = 0; j < inputs.length; j++) {
                    pers.push($(inputs[j]).prop('checked') === true ? 1 : 0)
                }
                var permission = "," + pers.toString() + ",";
                var param = {
                    user_id: info.user_id,
                    project_id: currentProjectId,
                    permission: permission
                }
                patch('/api/cgDuty/updatePer', param, function () {
                    layer.close(index)
                    layer.msg('配置成功');
                })
            })
        });
    }
</script>
